#include "pch.hpp"
#include "Dialog.hpp"
#include "WidgetImpl.hpp"
#include "WinException.hpp"

using namespace WinUi;




Dialog::Dialog(Window* parent)
	: Window(parent, L"Dialog", calculatePos(parent, int2(100, 100)), int2(100, 100), WS_POPUP | WS_CAPTION)
{
	ShowWindow(d->wnd, SW_SHOWDEFAULT);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

Dialog::Dialog(const std::wstring& title, Window* parent)
	: Window(parent, L"Dialog", calculatePos(parent, int2(100, 100)), int2(100, 100), WS_POPUP | WS_CAPTION)
{
	setText(title);
	ShowWindow(d->wnd, SW_SHOWDEFAULT);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

Dialog::~Dialog()
{}
///////////////////////////////////////////////////////////////////////////////////////////////////




int Dialog::exec()
{
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));
	while(msg.message != WM_NCDESTROY)
	{
		if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		else
		{
			boost::this_thread::sleep(boost::posix_time::millisec(1));
		}
	}

	// On Win64, this WPARAM happens to be a LONG_PTR, thus being bigger
	// than int, however since even WinMain() returns an integer, it will
	// be safe to do so here as well.
	return static_cast<int>(msg.wParam);
}
///////////////////////////////////////////////////////////////////////////////////////////////////




int2 Dialog::calculatePos(Window* parent, int2 size)
{
	int2 parentPos;
	int2 parentSize;

	if(parent)
	{
		parentPos  = parent->pos();
		parentSize = parent->size();
	}
	else
	{
		// The dialog is a toplevel window
		// We query the size of the desktop and place the dialog in the middle
		HWND desktop = GetDesktopWindow();
		RECT rect;
		WIN_API(GetWindowRect(desktop, &rect));

		parentPos = int2(0, 0);
		parentSize.x = rect.right - rect.left;
		parentSize.y = rect.top - rect.bottom;
	}

	parentSize.x = std::abs(parentSize.x);
	parentSize.y = std::abs(parentSize.y);

	// That's the center of the parent window
	int2 center;
	center.x = parentPos.x + parentSize.x / 2;
	center.y = parentPos.y + parentSize.y / 2;

	// Now calculate the position of the upper left corner of the dialog
	// while taking into account it's size
	int2 pos;
	pos.x = center.x - size.x / 2;
	pos.y = center.y - size.y / 2;

	return pos;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
